package com.guigui.gulimall.order.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigui.common.exception.NoStockException;
import com.guigui.common.to.MemberDto;
import com.guigui.common.to.OrderTo;
import com.guigui.gulimall.order.dto.OrderSubmitDto;
import com.guigui.gulimall.order.entity.OrderEntity;
import com.guigui.gulimall.order.entity.OrderItemEntity;
import com.guigui.gulimall.order.interceptor.GulimallAuthInterceptor;
import com.guigui.gulimall.order.service.OrderService;
import com.guigui.gulimall.order.to.OrderCreateTo;
import com.guigui.gulimall.order.vo.OrderListVo;
import com.guigui.gulimall.order.vo.OrderSubmitSuccessVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class WebOrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitDto submitDto) {

        OrderSubmitSuccessVo orderSubmitSuccess;
        try {
            orderSubmitSuccess = orderService.submitOrder(submitDto);
        } catch (NoStockException e) {
            return "redirect:http://order.gulimall.com/confirm.html";
        }
        return "redirect:http://order.gulimall.com/pay?orderSn=" + orderSubmitSuccess.getOrder().getOrder().getOrderSn();
    }

    @GetMapping("/list")
    public String getOrderList(Model model) {

        List<OrderListVo> orderList = orderService.getOrderList();
        model.addAttribute("orderList", orderList);
        return "list";
    }

    @GetMapping("/detail.html")
    public String getOrderDetail(@RequestParam("orderSn") String orderSn, Model model) {
        OrderEntity orderDetail = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        model.addAttribute("orderDetail", orderDetail);
        return "detail";
    }

    @GetMapping("/pay")
    public String toPayPage(@RequestParam("orderSn") String orderSn, Model model) {
        OrderEntity byId = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        orderCreateTo.setOrder(byId);
//        new orderto
        model.addAttribute("confirmResult", orderCreateTo);
        return "pay";
    }

}
